package org.gitee.weapp.controller;

import org.gitee.weapp.domain.AjaxResult;
import org.gitee.weapp.domain.entity.AddressInfo;
import org.gitee.weapp.domain.entity.SysUser;
import org.gitee.weapp.mapper.AddressInfoMapper;
import org.gitee.weapp.mapper.DouAreaMapper;
import org.gitee.weapp.service.AddressService;
import org.gitee.weapp.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private DouAreaMapper douAreaMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private AddressInfoMapper addressInfoMapper;

    @Autowired
    private AddressService addressService;

    @GetMapping("/province")
    public AjaxResult getProvinceList() {
        return AjaxResult.success(douAreaMapper.getProvinceList());
    }

    @GetMapping("/area")
    public AjaxResult getAreaList(@RequestParam("name") String name) {
        return AjaxResult.success(douAreaMapper.getNameListByParentName(name));
    }

    @GetMapping("/list")
    public AjaxResult getAddressList() {
        SysUser sysUser = tokenService.getSysUserFromToken(request);
        if (null == sysUser) {
            return AjaxResult.error("用户未登录");
        }
        List<AddressInfo> list = addressInfoMapper.getAddressList(sysUser.getOpenId());
        return AjaxResult.success(list);
    }

    @PostMapping("/add")
    public AjaxResult addAddress(@RequestBody AddressInfo addressInfo) {
        SysUser sysUser = tokenService.getSysUserFromToken(request);
        if (null == sysUser) {
            return AjaxResult.error("用户未登录");
        }
        addressInfo.setOpenId(sysUser.getOpenId());
        addressService.addAddress(addressInfo);
        return AjaxResult.success();
    }

    @PutMapping("/edit")
    public AjaxResult editAddress(@RequestBody AddressInfo addressInfo) {
        SysUser sysUser = tokenService.getSysUserFromToken(request);
        if (null == sysUser) {
            return AjaxResult.error("用户未登录");
        }
        addressInfo.setOpenId(sysUser.getOpenId());
        addressService.editAddress(addressInfo);
        return AjaxResult.success();
    }

    @DeleteMapping("/delete")
    public AjaxResult deleteAddress(@RequestParam("id") Integer id) {
        SysUser sysUser = tokenService.getSysUserFromToken(request);
        if (null == sysUser) {
            return AjaxResult.error("用户未登录");
        }
        addressInfoMapper.delete(id);
        return AjaxResult.success("删除成功");
    }
}
